import { console } from "inspector";
import { ProductService } from "../../../services/product.service.js";
import { NotFoundError, BadRequestError } from "../../../utils/errors.js";
import { db } from "./../../../config/sequelize.js";

const productService = new ProductService(db);
/**
 * Admin 商品管理控制器
 */
export class AdminProductController {
  constructor(ProductService) {
    console.log("商品服务：", ProductService);
    this.productService = ProductService;
  }
  /**
   * 获取商品分类列表
   */
  static async getCategoryList(req, res) {
    const categoryList = await productService.getCategoryList();
    res.json({
      code: 200,
      success: true,
      data: categoryList,
    });
  }
  /**
   * 获取商品列表（带分页和筛选）
   */
  static async getProductsList(req, res) {
    const {
      page,
      limit,
      search,
      status,
      category_id,
      minPrice,
      maxPrice,
      sortBy,
      order,
    } = req.validatedData;
    const { data, pagination } = await productService.getProductList({
      page,
      limit,
      filters: {
        search,
        status,
        category_id,
        priceRange: [minPrice, maxPrice],
      },
      sort: { field: sortBy, order },
      isAdmin: true,
      withSkus: false, // 是否关联SKU信息
    });

    res.json({
      code: 200,
      success: true,
      data: { list: data, pagination },
    });
  }

  /**
   * 获取商品详情
   */
  static async getProductInfo(req, res) {
    const { id } = req.params;
    // 从中间件获取管理员权限
    // const { isAdmin } = req.user; // 从中间件获取
    // 前端传值，控制更灵活
    const { isAdmin } = req.query;
    console.log("是否是管理员:", isAdmin);

    const product = await productService.getProductById(id);

    if (!product) {
      throw new NotFoundError("商品不存在");
    }
    // 获取商品规格
    const specs = await productService.getProductSpecs(id);
    // 获取该商品下的所有SKU
    const skus = await productService.getSkuById(id, isAdmin);

    // 处理数据转换
    const productData = product.get ? product.get({ plain: true }) : product;
    const skusData = skus
      ? skus.map((sku) => (sku.get ? sku.get({ plain: true }) : sku))
      : [];

    res.status(200).json({
      code: 200,
      success: true,
      data: {
        data: {
          ...productData,
          specs,
          skus: skusData,
        },
      },
    });
  }

  /**
   * 获取商品规格列表
   */
  static async getProductSkuList(req, res) {
    const productId = req.params.id; // 从请求参数中获取商品ID

    const { isAdmin } = req.query;
    const specList = await productService.getSkuById(productId, isAdmin);
    res.json({
      code: 200,
      id: productId,
      success: true,
      data: {data:{ skus: specList }},
    });
  }
  /**
   * 创建商品
   */
  static async createProduct(req, res) {
    const productData = req.validatedData;
    console.log("前端数据：", productData);
    if (!productData) {
      throw new BadRequestError("请求数据格式异常");
    }
    // 验证必填字段
    if (!productData.name || !productData.price || !productData.category_id) {
      throw new BadRequestError("商品名称、价格和分类是必填字段");
    }

    // 检查SKU唯一性
    if (productData.sku) {
      const skuExists = await productService.checkSkuExists(productData.sku);
      if (skuExists) {
        throw new BadRequestError("SKU已存在");
      }
    }

    const product = await productService.createProduct(productData);

    res.status(200).json({
      code: 200,
      success: true,
      data: product,
      message: "商品创建成功",
    });
  }

  /**
   * 更新商品信息
   */
  static async updateProduct(req, res) {
    console.log("前端数据-更新商品：", req.validatedData);
    const { id } = req.params;
    const updateData = req.validatedData;

    // 检查SKU是否被修改且是否唯一
    if (updateData.sku) {
      const skuExists = await productService.checkSkuExists(updateData.sku, id);
      if (skuExists) {
        throw new BadRequestError("SKU已存在");
      }
    }

    const product = await productService.updateProduct(id, updateData);

    if (!product) {
      throw new NotFoundError("商品不存在");
    }

    res.json({
      code: 200,
      success: true,
      data: product,
      message: "商品更新成功",
    });
  }

  /**
   * 批量删除商品
   */
  static async batchDeleteProducts(req, res) {
    if (!req.validatedData?.ids) {
      throw new BadRequestError("请求数据格式异常");
    }

    const ids = req.validatedData.ids.map((id) =>
      typeof id === "string" && /^\d+$/.test(id) ? Number(id) : id
    );

    const result = await productService.batchDeleteProducts(ids);

    if (result.length === 0) {
      throw new NotFoundError("没有找到要删除的商品");
    }

    res.json({
      code: 200,
      success: true,
      message: "批量删除商品成功",
      data: result,
    });
  }

  /**
   * 删除商品 (软删除)
   */
  static async deleteProduct(req, res) {
    const { id } = req.params;
    const result = await productService.softDeleteProduct(id);

    if (!result) {
      throw new NotFoundError("商品不存在");
    }

    res.json({
      success: true,
      message: "商品已标记为删除",
    });
  }

  /**
   * 恢复已删除商品
   */
  static async restoreProduct(req, res) {
    const { id } = req.params;
    const product = await productService.restoreProduct(id);

    if (!product) {
      throw new NotFoundError("商品不存在或未被删除");
    }

    res.json({
      success: true,
      data: product,
      message: "商品恢复成功",
    });
  }

  /**
   * 更新商品状态
   */
  static async updateProductStatus(req, res) {
    const { id } = req.params;
    const { status } = req.validatedData;

    const product = await productService.updateProductStatus(id, status);

    if (!product) {
      throw new NotFoundError("商品不存在");
    }

    res.json({
      success: true,
      data: product,
      message: "商品状态更新成功",
    });
  }

  /**
   * 获取所有规格类型
   */
  static async getSpecTypeList(req, res) {
    const { id } = req.params;
    // 1. 参数校验（使用Joi或自定义校验）
    const { page = 1, pageSize = 10, keyword = "" } = req.query;
    console.log(page, pageSize, keyword);
    const specificationTypes = await productService.getSpecTypeList(id, {
      page,
      pageSize,
      keyword,
    });

    res.json({
      code: 200,
      success: true,
      data: specificationTypes,
    });
  }

  /**
   * 创建规格类型 createSpecType
   */
  static async createSpecType(req, res) {
    const { id } = req.params;
    const { name, values, description } = req.body;
    console.log("前端数据：", name, values, description);
    const specificationType = await productService.createSpecType(
      id,
      name,
      values,
      description
    );

    res.json({
      code: 200,
      success: true,
      data: specificationType,
      message: "规格类型创建成功",
    });
  }

  /**
   * 更新规格类型  updateSpecType
   */
  static async updateSpecType(req, res) {
    const { id } = req.params;
    console.log("更新id:", id);
    const { name, values, description } = req.body;
    const specificationType = await productService.updateSpecType(
      id,
      name,
      values,
      description
    );

    res.json({
      code: 200,
      success: true,
      data: specificationType,
      message: "规格类型更新成功",
    });
  }

  /**
   * 删除规格类型 ，软删除 deleteSpecType
   */
  static async deleteSpecType(req, res) {
    const { id } = req.params;
    const specificationType = await productService.deleteSpecType(id);

    res.json({
      code: 200,
      success: true,
      data: specificationType,
      message: "规格类型删除成功",
    });
  }

  /**
   * 批量删除规格类型  batchDeleteSpecTypes
   */
}
